import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import { Form, Col, Divider, Spin, Button, Radio, DatePicker, Modal, AutoComplete, Input, Tooltip, Icon, Select } from 'antd';
import prompt from '@/components/Prompt';
import EditPage from '@/components/EditPage';
import AntdForm from '@/components/AntdForm';
import AdModal from '@/components/AdModal';

import StandardTable from '@/components/StandardTable';
import router from 'umi/router';
import AdSelect from '@/components/AdSelect';
import AntdFormItem from '@/components/AntdFormItem';
import AntdInput from '@/components/AntdInput';
import FileReader from '@/components/FileReader';
import AdButton from '@/components/AdButton';
import SearchSelect from '@/components/SearchSelect';
import AntdDatePicker from '@/components/AntdDatePicker';
import IncidentalInfo from './IncidentalInfo';
import querystring from 'querystring';
import moment from 'moment';
import {
    formItemFragement,
    queryDict,
    filterAddFile,
    filterDeteteFile,
    formatPrice,
} from '@/utils/common';
import { checkStrLength, columnsDriver, columns1 } from '@/pages/Common/common';

import { allDictList } from '@/utils/constans';
import PressureInfo from './PressureInfo';
import ArchivesDriverslInfo from './ArchivesDriverslInfo';
import {
    selectArchivesList,
    selectArchivesDetailAndInfo,
    routeUrl,
    allUrl,
    codes,
    allDispatchType,
    archivesStatusList,
    checkConfirm,
    sendSomeList,
    DateMinus,
} from './utils';
import styles from './archives.less';

const { confirm } = Modal;
const { TextArea } = Input;
const dateFormatTime = 'YYYY-MM-DD HH:mm';
const dateFormat = 'YYYY-MM-DD';
const dateFormatByM = 'YYYY-MM';
const { Option } = Select;
const { MonthPicker } = DatePicker;

@connect(({ Archives, component, loading, common }) => ({
    Archives,
    trainInfoList: Archives.trainInfoList,
    archivesDetail: Archives.archivesDetail,
    pressureInfoList: Archives.pressureInfoList,
    oilInfoList: Archives.oilInfoList,
    feeData: Archives.feeData,
    dictObject: component.dictObject,
    formValues: Archives.formValues,
    loading: loading.effects[allDispatchType.detail],
    panes: common.panes,
    incidentalInfoList: Archives.incidentalInfoList,
    getCostAccount: Archives.getCostAccount
}))
@Form.create()
export default class ArchivesOperateHK extends Component {
    constructor(props) {
        super(props)
        const {
            form: { getFieldDecorator },
        } = props;
        this.state = {
            detailId: '',
            selectedRows: [],
            type: '',
            selectedRowsPre: [],
            selectedRowsInd: [],
            disabled: false,
            visibleOperate: false,
            showTips: false,
            showTipsInd: false,
            isHK: true,
            drivers: [],
            hkDriver:[],
            trainId: '',
            placeHKList: [],
            crossHkList:[],
            fileListL: [],
            costType: [],
            visibleRemove: false
            //  driversIID:[],
        };
        this.commonParams = {
            getFieldDecorator,
        };
    }


    columns = [
        {
            title: '单据号',
            dataIndex: 'miscellaneousNo',
            width: 140,
            render: (text, record) => {
                const { dictObject, onlyRead } = this.props;
                const { disabled } = this.state;
                if (!onlyRead) {
                    return (
                        <AntdFormItem
                            label=" "
                            code={`miscellaneousNo-${record.id}`}
                            initialValue={text}
                            {...this.commonParams}
                        >
                            <AntdInput
                                disabled={true}
                                onChange={value => this.handleFieldChange(value, 'miscellaneousNo', record.id)}
                                placeholder="保存后系统自动生成"
                            />
                        </AntdFormItem>
                    );
                }
                return <span>{text}</span>;
            },
        },
        // {
        //     title:'是否已生成账单',
        //     dataIndex:'billStatus',
        //     width:130,
        //     render:(text,record)=>{
        //         const { dictObject, onlyRead, disabled } = this.props;
        //         if (!onlyRead) {
        //             return (
        //                 <AntdFormItem
        //                     label=" "
        //                     code={`billStatus-${record.id}`}
        //                     initialValue={text}
        //                     {...this.commonParams}
        //                 >
        //                     <AntdInput
        //                         disabled={true}
        //                         onChange={value => this.handleFieldChange(value, 'billStatus', record.id)}
        //                         placeholder="保存后系统自动生成"
        //                     />
        //                 </AntdFormItem>
        //             );
        //         }
        //         return <span>{text==='true'?'是':'否'}</span>;
        //     }
        // },
        {
            title: '费用类型',
            dataIndex: 'type',
            width: 130,
            render: (text, record) => {
                const { dictObject, onlyRead } = this.props;
                const { disabled } = this.state;
                if (!onlyRead) {
                    return (
                        <AntdFormItem
                            label=" "
                            code={`type-${record.id}`}
                            initialValue={text}
                            {...this.commonParams}
                            rules={[{ required: true }]}
                        >
                            <AdSelect
                                disabled={record.isBill === 'true'}
                                isExist={true}

                                data={dictObject[allDictList.otherFeeType]}
                                payload={{ code: allDictList.otherFeeType }}
                                onChange={value => this.handleFieldChange(value, 'type', record.id)}
                            />
                        </AntdFormItem>
                    );
                }
                return renderTableAdSelect({
                    props: this.props,
                    value: text,
                    key: allDictList.otherFeeType,
                });
            },
        },

        {
            title: '科目',
            dataIndex: 'costType',
            width: 250,
            render: (text, record) => {
                const { dictObject, onlyRead, dispatch } = this.props;
                const { disabled } = this.state;

                if (!onlyRead) {
                    return (
                        <AntdFormItem
                            label=" "
                            code={`costType-${record.id}`}
                            initialValue={text}
                            {...this.commonParams}
                            rules={[{ required: true }]}
                        >
                            <AdSelect
                                disabled={record.isBill === 'true'}
                                isExist={true}
                                data={dictObject[allDictList.costSubjects]}
                                payload={{ code: allDictList.costSubjects }}
                                onChange={value => this.handleFieldChange(value, 'costType', record.id)}
                            />
                        </AntdFormItem>
                    );
                }
                return renderTableAdSelect({
                    props: this.props,
                    value: text,
                    key: allDictList.costSubjects,
                });
            },
        },
        {
            title: '费用标识',
            dataIndex: 'costTag',
            width: 230,
            render: (text, record) => {
                const { dictObject, onlyRead, } = this.props;
                const { disabled } = this.state;
                if (!onlyRead) {
                    return (
                        <AntdFormItem
                            label=" "
                            code={`costTag-${record.id}`}
                            initialValue={text}
                            {...this.commonParams}
                            rules={[{ required: true }]}
                        >
                            <AdSelect
                                disabled={record.isBill === 'true'}
                                isExist={true}
                                // multiple={true}
                                // mode="multiple" 
                                data={dictObject[allDictList.costTag]}
                                payload={{ code: allDictList.costTag }}
                                onChange={value => this.handleFieldChange(value, 'costTag', record.id)}
                            />

                        </AntdFormItem>
                    );
                }
                return renderTableAdSelect({
                    props: this.props,
                    value: text,
                    key: allDictList.costTag,
                });
            },
        },
        {
            title: '时间',
            dataIndex: 'happenTime',
            width: 140,
            render: (text, record) => {
                const { dictObject, onlyRead } = this.props;
                const { disabled } = this.state;
                if (!onlyRead) {
                    return (
                        <AntdFormItem
                            label=" "
                            code={`happenTime-${record.id}`}
                            initialValue={text ? moment(text, dateFormat) : null}
                            {...this.commonParams}
                            rules={[{ required: true }]}
                        >
                            <AntdDatePicker
                                disabled={record.isBill === 'true'}
                                onChange={value => this.handleFieldChange(value, 'happenTime', record.id)}
                            />
                        </AntdFormItem>
                    );
                }
                return <span>{text}</span>;
            },
        },
        {
            title: '司机',
            dataIndex: 'driverId',
            width: 260,
            render: (text, record) => {
                const { dictObject, onlyRead } = this.props;
                const { drivers } = this.state;
                let driversIID = drivers.map(item => { return item.id });
                const { disabled } = this.state;
                if (!onlyRead) {
                    return (
                        <AntdFormItem
                            label=" "
                            code={`driverId-${record.id}`}
                            initialValue={record.driverId ? [{ id: record.driverId }] : ''}
                            rules={[{ required: true }]}
                            {...this.commonParams}
                        >
                            <SearchSelect
                                dataUrl="tms/tms-driver-archives/selectDriverList"
                                url="tms/tms-driver-archives/selectDriverView_s"
                                payload={{ 'driverSort': driversIID }}
                                multiple={false} // 是否多选
                                selectedData={record.drivers || [{ id: record.driverId }]} // 选中值
                                columns={columnsDriver} // 表格展示列
                                onChange={value => this.handleFieldChange(value, 'driverId', record.id, 'drivers')}
                                id="ArchivesOperate_2"
                                disabled={record.isBill === 'true'}
                                allowClear={false}

                            />
                        </AntdFormItem>
                    );
                }
                return <span>{record.driverName}</span>;
            },
        },
        {
            title: '金额(元)',
            dataIndex: 'fee',
            width: 120,
            render: (text, record) => {
                const { onlyRead } = this.props;
                const { disabled } = this.state;
                if (!onlyRead) {
                    return (
                        <AntdFormItem
                            label=" "
                            code={`fee-${record.id}`}
                            initialValue={formatPrice(text)}
                            {...this.commonParams}
                            rules={[{ required: true }]}
                        >
                            <AntdInput
                                mode="money"
                                disabled={record.isBill === 'true'}
                                onChange={value => this.handleFieldChange(value, 'fee', record.id)}
                            />
                        </AntdFormItem>
                    );
                }
                return formatPrice(text);
            },
        },
        {
            title: '币种',
            dataIndex: 'currency',
            width: 130,
            render: (text, record) => {
                const { dictObject, onlyRead } = this.props;
                const { disabled } = this.state;
                if (!onlyRead) {
                    return (
                        <AntdFormItem
                            label=" "
                            code={`currency-${record.id}`}
                            initialValue={text || 'CNY'}
                            {...this.commonParams}
                            rules={[{ required: true }]}
                        >
                            <AdSelect
                                disabled={record.isBill === 'true'}
                                data={dictObject[allDictList.currencyType]}
                                payload={{ code: allDictList.currencyType }}
                                onChange={value => this.handleFieldChange(value, 'currency', record.id)}
                            />
                        </AntdFormItem>
                    );
                }
                return renderTableAdSelect({
                    props: this.props,
                    value: text,
                    key: allDictList.currencyType,
                });
            },
        },
        {
            title: '备注',
            dataIndex: 'remark',
            width: 150,
            render: (text, record) => {
                const { onlyRead } = this.props;
                const { disabled } = this.state;
                if (!onlyRead) {
                    return (
                        <AntdInput
                            value={text}
                            disabled={record.isBill === 'true'}
                            node="number"
                            onChange={value => this.handleFieldChange(value, 'remark', record.id)}
                        />
                    );
                }
                return text;
            },
        },
        {
            title: '附件',
            dataIndex: 'fileTokens',
            width: 200,
            render: (text, record) => {
                const { onlyRead } = this.props;
                const { disabled } = this.state;
                const _text = record.attaQuantity;
                if (!onlyRead) {
                    return (
                        <AntdFormItem
                            label=" "
                            code={`fileTokens-${record.id}`}
                            initialValue={record.fileList || []}
                            {...this.commonParams}
                        >
                            <FileReader
                                urlType="tms"
                                onChange={value => this.handleFieldChange(value, 'fileTokens', record.id)}
                                disabled={record.isBill === 'true'}
                            />
                        </AntdFormItem>
                    );
                }
                return (
                    _text &&
                    Number(_text) > 0 && (
                        <Badge className="cus_badge" count={_text}>
                            <div className="head-example">
                                <FileReader
                                    type="list"
                                    count={_text}
                                    urlType="tms"
                                    params={{ bizId: record.id, fileBizType: 'MISCELLANEOUS' }}
                                />
                            </div>
                        </Badge>
                    )
                );
            },
        },
    ];


    componentWillMount() {
        let allDict = [allDictList.businessType, allDictList.cabinetTypeHK, allDictList.straightAddress, allDictList.archives_place];
        //杂费的
        allDict = [...allDict, allDictList.currencyType, allDictList.otherFeeType, allDictList.costSubjects, allDictList.costTag];
        queryDict({ props: this.props, allDict });
    }

    componentDidMount() {
        const {
            match: {
                params: { id },
            },
            archivesDetail,
            dispatch
        } = this.props;
        this.handleStateChange([{ detailId: id }]);
        this.getArchivesDetails(id);
        dispatch({
            type: 'common/querytDictByCode',
            payload: { code: allDictList.transfer_placeHK },
            callback: (res) => {
                this.setState({
                    placeHKList: res.map(v => v.value)
                })
            }
        })
        dispatch({
            type: 'common/querytDictByCode',
            payload: { code: allDictList.transfer_crossHK },
            callback: (res) => {
                this.setState({
                    crossHkList: res.map(v => v.value)
                })
            }
        })
    }


    //杂费的 ---- start
    getIncidentalInfoList = (id) => {
        const { dispatch } = this.props;
        dispatch({
            type: allDispatchType.incidentalInfoList,
            payload: { id },
            callback: data => {
                let newData = data;
                newData.map(v => {
                    if (v.attaQuantity > 0) {
                        dispatch({
                            type: allDispatchType.selectFileList,
                            payload: { bizId: v.id, fileBizType: 'MISCELLANEOUS' },
                            callback: data => {
                                v.fileList = data;
                                // this.setState({
                                //     fileList:v.fileList
                                // })
                                this.saveAllValue({
                                    incidentalInfoList: { [this.state.trainId]: { list: newData } },
                                });
                            },
                        });
                    }
                });
            },
        });
    };

    getAddDataObj = () => {
        return {
            id: `isNew${Math.ceil(Math.random() * 10000) + 10000}`,
            miscellaneousNo: '',
            type: '',
            costTag: '',
            happenTime: '',
            fee: '',
            currency: 'CNY',
            remark: '',
            fileTokens: [],
            driverId: '',
        };
    };
    //添加
    addInfoInd = (e) => {
        e && e.stopPropagation();
        const { detailId, trainId } = this.state;
        let newData = this.getInfoData();
        newData = [this.getAddDataObj(), ...newData];
        this.saveAllValue({ incidentalInfoList: { [trainId]: { list: newData } } });
    };
    //拉取杂费：
    pullInfoInd = (e) => {
        e && e.stopPropagation();
        const { detailId, trainId } = this.state;
        const { dispatch } = this.props;

        dispatch({
            type: allDispatchType.pullIncidentals,
            payload: { id: detailId },
            callback: (res) => {
                this.getIncidentalInfoList(trainId)
            },
        });
    }

    getInfoData = (costT, id) => {
        const { incidentalInfoList } = this.props;
        const { detailId, trainId } = this.state;
        let newData = [];
        if (incidentalInfoList[trainId]) {
            const data = incidentalInfoList[trainId].list;
            newData = data.map(item => {
                let { costType, ...value } = item
                if (!item.id && costT) {
                    costType = costT
                } else if (item.id == id) {
                    console.log('item.id,id', item.id, id)
                    costType = costT
                }

                return ({ costType, ...value })
            });
            // console.log('trainId', trainId, incidentalInfoList[trainId].list, newData)

        }
        return newData;
    };

    getRowByKey(id, newData) {
        const data = this.getInfoData();
        return (newData || data).filter(item => item.id === id)[0];
    }

    handleFieldChange(value, fieldName, id, fieldName2, costT) {
        // console.log('value, fieldName, id', value, fieldName, id)
        const { detailId, trainId, costType } = this.state;
        console.log(value, 'costType', costType)
        const { dispatch, dictObject, form } = this.props;
        this.showTipsFunInd(true);
        let newData = this.getInfoData();
        const target = this.getRowByKey(id, newData);

        if (target) {
            target[fieldName] = value;
        }
        //费用类型带出 科目
        if (fieldName === 'type') {
            let obj = dictObject[allDictList.otherFeeType].find(item => item.code === value)
            // 因为手动选择的优先级大于自动带出的默认的值， 所以当 costType被手动选择后，再点费用类型会带不出科目；需要调用
            // form.setFieldsValue去手动设置表格中 的显示的值
            form.setFieldsValue({ [`costType-${target.id}`]: obj.remarks });
            // 表格中设置显示 值后，需要把设置的值保存到 后台
            target.costType = obj.remarks;
        }
        if (fieldName === 'happenTime') {
            if (value) {
                target.happenTime = moment(value).format(dateFormat);
            }
        } else if (fieldName === 'fileTokens') {
            target.fileTokens = filterAddFile(value) || [];
            target.deleteFileIds = filterDeteteFile(value, target.fileList || []) || []; //测试
        }

        if (fieldName == 'driverId') {
            target[fieldName] = value[0].id;
            target[fieldName2] = value;
        }

        this.saveAllValue({ incidentalInfoList: { [trainId]: { list: newData } } });
    }
    //杂费的 ---- end

    getArchivesDetails = (id) => {
        const {
            match: { params },
        } = this.props;
        const { isHK } = this.state;
        const archivesId = id || params.id;
        selectArchivesDetailAndInfo({
            type: allDispatchType.detail,
            payload: { id: archivesId, isHK },
            props: this.props,
            callback: data => {
                if (data.status == 'SUBMITTED') {
                    this.setState({
                        disabled: true,
                    });
                }
                const detail =this.props.archivesDetail[id] ;
                this.setState({
                    type: data.type,
                    drivers: data.trainInfo ? data.trainInfo.driverMap || [] : [],
                    trainId: data.trainInfo.id,
                    hkDriver:data.trainInfo ? data.trainInfo.hkDriver||[] : [],
                    businessType:detail.businessType
                });
                //杂费的
                this.getIncidentalInfoList(data.trainInfo.id);
            },
        });
    };

    handleStateChange = (options = []) => {
        options.map(item => {
            this.setState(item);
        });
    };

    //保存(确认、试算、提交)
    saveInfo = type => {
        const {
            form,
            archivesDetail,
            match: {
                params: { id },
            },
            pressureInfoList,
            feeData,
            incidentalInfoList
        } = this.props;

        const { drivers,hkDriver, isHK, trainId } = this.state;
        if (type == 'commit' && feeData && feeData[id]) {
            this.dispatchOperate({}, type);
            return;
        }

        form.validateFieldsAndScroll((err, values) => {

            let newValues = {}
            for (let k in values) {
                if (k.indexOf('isNew') == -1) {
                    newValues[k] = values[k]
                }
            }
            const {
                status,
                attaQuantity,
                mdsCompanyId,
                transportEndTime,
                transportStartTime,
                settlementDate,
                ...params
            } = newValues;

            const startTime = transportStartTime ? moment(transportStartTime).format(dateFormatTime) : '';
            const endTime = transportEndTime ? moment(transportEndTime).format(dateFormatTime) : '';
            params.transportStartTime = startTime;
            params.transportEndTime = endTime;
            params.settlementDate = settlementDate ? moment(settlementDate).format(dateFormatByM) : '';

            //司机
            if (drivers.length > 0) {
                params.driverIds = drivers.map(v => {
                    return v.id;
                });
            }
            if(hkDriver.length>0){
                params.hkDriver=hkDriver.map(v=>v.id)
            }
            params.isHK = isHK;

            params.operateType = type;
            if (attaQuantity) {
                params.fileTokens = filterAddFile(attaQuantity);
            }
            if (id) {
                params.id = id;
                if (attaQuantity) {
                    params.deleteFileIds = filterDeteteFile(attaQuantity, archivesDetail[id].fileList);
                }
            }

            //2、校验杂费
            // const infoForm = this.child.props.form;
            let relationVOSInd = [];
            // infoForm.validateFieldsAndScroll(errors => {
            // if (err || errors) return;
            const days = DateMinus(startTime, endTime);
            if (Number(params.startMileage) > Number(params.collectMileage)) {
                prompt({ content: '收车里程必须大于发车里程！', type: 'error' });
                return;
            }
            console.log('杂费明细=incidentalInfoList', incidentalInfoList)
            if (id) {
                relationVOSInd = incidentalInfoList[trainId] && incidentalInfoList[trainId].list.map(item => {
                    const { drivers, ...restd } = item;
                    if (item.id.includes('isNew')) {
                        const { id, ...rest } = restd;
                        return rest;
                    }
                    return restd;
                });
            } else {
                relationVOSInd =
                    Object.keys(incidentalInfoList).length > 0 ? incidentalInfoList[''].list : [];
                relationVOSInd = incidentalInfoList[trainId].list.map(item => {
                    const { drivers, ...rest } = item;
                    return rest;
                });
            }
            params.miscellaneousList = relationVOSInd; //杂费
            // console.log('params.miscellaneousList----',params.miscellaneousList)
            //3、校验压夜
            const infoForm = this.child.props.form;
            let relationVOS = [];

            infoForm.validateFieldsAndScroll(errors => {
                if (err || errors) return;
                //余额校验
                const etcStartAmount = params.etcStartAmount || 0;
                const etcEndAmount = params.etcEndAmount || 0;
                if (Number(etcStartAmount) < Number(etcEndAmount)) {
                    prompt({ content: '发车余额必须大于等于收车余额!', type: 'error' });
                    return;
                }

                if (id) {
                    relationVOS = pressureInfoList[id].list.map(item => {
                        const { driverMap, ...restd } = item;
                        if (item.id.includes('isNew')) {
                            const { id, ...rest } = restd;
                            return rest;
                        }
                        // if(!item.currency){
                        //     item.currency='CNY'
                        // }
                        return restd;
                    });
                } else {
                    relationVOS =
                        Object.keys(pressureInfoList).length > 0
                            ? pressureInfoList[''].list.map(item => {
                                const { driverMap, ...rest } = item;
                                return rest;
                            })
                            : [];
                }
                params.nightList = relationVOS; //压夜

                this.dispatchOperate(params, type);
            });
        });
    };

    /************操作：
    1、草稿：
    1）确认：保存数据-->确认校验-->已确认
    2、已确认：
    1)试算：保存数据-->确认校验-->试算接口-->生成费用
    2)提交：(先判断有没有费用数据)
    没有：保存数据-->确认校验-->试算接口-->生成费用(并提示费用已计算，是否进行提交)-->提交接口
    有：提交接口（提交后数据将不能编辑，是否进行提交？
    */
    dispatchOperate = (params, type) => {
        const { dispatch, formValues, feeData } = this.props;
        const { isHK } = this.state;
        const id = params.id;
        const unit = {
            callDispatch: data => {

                this.setState(preState => ({
                    disabled: type == 'confirm' ? true : !preState.disabled,
                    showTips: false,
                    showTipsInd: false,
                }));
                if (id) {
                    this.getArchivesDetails(id);
                    this.pressureInfoList(id);
                }
                selectArchivesList({ payload: formValues, props: this.props });
            },
            callCommit: tips => {
                const {
                    dispatch,
                    match: {
                        params: { id },
                    },
                    formValues,
                } = this.props;
                confirm({
                    title: `${tips}提交后数据将不能进行修改，是否进行提交？`,
                    content: ' ',
                    okText: '确定',
                    cancelText: '取消',
                    onOk: () => {
                        dispatch({
                            type: allDispatchType.commit,
                            payload: { ids: [id] },
                            callback: data => {
                                if (!data) return;
                                selectArchivesList({ props: this.props, payload: formValues });
                                this.getArchivesDetails(id);
                                this.pressureInfoList(id);
                            },
                        });
                    },
                });
            },
        };
        if (type == 'commit' && feeData && feeData[id]) {
            unit.callCommit();
            return;
        }

        dispatch({
            type: allDispatchType.operate,
            payload: params,
            callback: data => {
                // if (!data) return;

                if (type == 'save') {
                    unit.callDispatch(data);
                } else {
                    checkConfirm({
                        props: this.props,
                        id,
                        type,
                        isHK,
                        callback: () => {
                            // return; //测试
                            if (type == 'confirm') {
                                //审核确认
                                dispatch({
                                    type: allDispatchType.confirm,
                                    payload: { id },
                                    callback: data => {
                                        unit.callDispatch(data);
                                    },
                                });
                            } else {
                                //试算和提交
                                dispatch({
                                    type: allDispatchType.trial,
                                    payload: { id, type },
                                    callback: data => {
                                        unit.callDispatch(data);
                                        //试算完数据回显处理：未做
                                        if (type == 'commit') {
                                            const tips = '费用已计算，';
                                            unit.callCommit(tips);
                                        }
                                    },
                                });
                            }
                        },
                    });
                }
            },
        });
    };
    //压夜列表
    pressureInfoList = id => {
        const { dispatch, } = this.props;
        const { drivers } = this.state;
        dispatch({
            type: allDispatchType.pressureInfoList,
            payload: { id },
        });
    };

    infoOilAdd = e => {
        e.stopPropagation();
        this.setOilInfoModal('add');
    };
    setOilInfoModal = type => {
        const { visibleOperate } = this.state;
        this.setState({
            visibleOperate: !visibleOperate,
            type,
        });
    };

    headerOperate = () => {
        const {
            match: {
                params: { id },
            },
            archivesDetail,
        } = this.props;
        const { disabled, detailId } = this.state;
        const detail = archivesDetail[detailId] || {};
        const isCONFIRM = detail.status == 'SUBMITTED' ? true : false;
        return (
            <div>
                {detail.status == 'SUBMITTED' || !disabled ? (
                    <>
                        <Button.Group>
                            <AdButton
                                text="保存"
                                type="primary"
                                code={codes.add}
                                onClick={() => this.saveInfo('save')}
                                disabled={false}
                            />
                            {detail.status !== 'SUBMITTED' && id && (
                                <AdButton
                                    onClick={() => {
                                        this.setState(preState => ({
                                            disabled: !preState.disabled,
                                        }));
                                    }}
                                    text="取消"
                                    code={id ? codes.edit : codes.add}
                                />
                            )}
                        </Button.Group>
                    </>
                ) : (
                        <Button.Group>
                            {id && detail.status == 'UNSEALED' && (
                                <AdButton
                                    text="审核确认"
                                    code={codes.confirm}
                                    onClick={() => this.saveInfo('confirm')}
                                    disabled={isCONFIRM}
                                />
                            )}
                            {detail.status == 'CONFIRM' && (
                                <>
                                    <AdButton
                                        text="费用试算"
                                        code={codes.trial}
                                        onClick={() => this.saveInfo('trial')}
                                        disabled={isCONFIRM}
                                    />
                                    <AdButton
                                        text="提交"
                                        code={codes.commit}
                                        onClick={() => this.saveInfo('commit')}
                                        disabled={isCONFIRM}
                                    />
                                </>
                            )}
                            <AdButton
                                onClick={() => {
                                    this.setState(preState => ({
                                        disabled: !preState.disabled,
                                    }));
                                }}
                                text="编辑"
                                type="primary"
                                disabled={isCONFIRM}
                                code={id ? codes.edit : codes.add}
                            />
                        </Button.Group>
                    )}
            </div>
        );
    };

    getValue = (values, type) => {
        this.setState({
            [type]: values,
        });
        // if (type == 'businessType') {
        //     if(values!=='HK_CROSS'){
        //         this.setState({hkDriver:[]})
        //         this.props.form.setFieldsValue({
        //             hkTransit:''
        //         })
        //     }
        // }
    };

    onRef = ref => {
        this.child = ref;
    };
    //添加压夜
    addInfoPre = e => {
        e.stopPropagation();
        this.child.addInfoPre();
    };
    //移除压夜
    removeInfoPre = e => {
        e.stopPropagation();
        const { detailId, selectedRowsPre } = this.state;
        const { pressureInfoList } = this.props;
        const deleteIds = selectedRowsPre.map(v => v.id);
        this.deleteInfoIds = selectedRowsPre.filter(item => !item.id.includes('isNew')).map(v => v.id);
        const newData = pressureInfoList[detailId].list.filter(item => !deleteIds.includes(item.id));
        this.saveAllValue({ pressureInfoList: { [detailId]: { list: newData } } });
        this.handleStateChange([{ selectedRowsPre: [], showTips: true }]);

    };
    //移除杂费
    removeInfoInd = () => {
        const { detailId, trainId, selectedRowsInd } = this.state;
        const { incidentalInfoList } = this.props;
        const deleteIds = selectedRowsInd.map(v => v.id);
        this.deleteInfoIds = selectedRowsInd.filter(item => !item.id.includes('isNew')).map(v => v.id);
        const newData = incidentalInfoList[trainId].list.filter(item => !deleteIds.includes(item.id));
        this.saveAllValue({ incidentalInfoList: { [trainId]: { list: newData } } });
        this.handleStateChange([{ selectedRowsInd: [], showTipsInd: true }]);
        this.setState({ visibleRemove: false })
    };
    saveAllValue = payload => {
        const { dispatch } = this.props;
        dispatch({
            type: allDispatchType.value,
            payload: payload || {},
        });
    };
    //表格显示提示--压夜：
    showTipsFun = val => {
        this.setState({
            showTips: val,
        });
    };

    //表格显示提示--杂费：
    showTipsFunInd = (val) => {
        this.setState({
            showTipsInd: val,
        });
    };

    render() {
        const {
            detailId,
            trainId,
            selectedRows,
            type,
            visibleOperate,
            selectedRowsInd,
            selectedRowsPre,
            disabled,
            showTips,
            showTipsInd,
            isHK,
            drivers,
            placeHKList,
            crossHkList,
            visibleRemove,
            businessType,
        } = this.state;
        let driversIID = drivers.map(item => { return item.id })
        const { form, archivesDetail, dictObject, loading, incidentalInfoList } = this.props;
        const getFieldDecorator = form.getFieldDecorator;
        const detail = archivesDetail[detailId] || {};
        console.log('businessType',businessType)
        //中港车取行车档案的详情
        const detailHK = detail ? detail.trainInfo || {} : {};
        const dataInd = incidentalInfoList[trainId] || {};

        const InciTitle = (
            <span>
                杂费明细
                {showTipsInd && (
                    <span style={{ color: 'red', marginLeft: 30 }}>当前数据有变化，请注意保存</span>
                )}
            </span>
        );
        const preTitle = (
            <span>
                压夜记录
                {showTips && (
                    <span style={{ color: 'red', marginLeft: 30 }}>当前数据有变化，请注意保存</span>
                )}
            </span>
        );

        let _disabled = true
        _disabled = selectedRowsInd && selectedRowsInd.every(v => v.isBill === 'false') ? false : true
        const editPageParams = {
            title: detail.archivesNo || '',
            headerOperate: this.headerOperate(),
            panelValue: [
                { key: '基础信息' },
                detailId &&
                detail.status !== 'UNSEALED' && {
                    key: '司机提成',
                },
                {
                    key: InciTitle,
                    extra: (
                        <div>
                            {/* <AdButton
                                onClick={e => {
                                    this.removeInfoInd(e,'confirm');
                                }}
                                ghost
                                disabled={disabled || selectedRowsInd.length === 0}
                                text="确认"
                                type="danger"
                            /> */}
                            <AdButton
                                onClick={e => {
                                    e.stopPropagation()
                                    this.setState({ visibleRemove: true })
                                    // this.removeInfoInd(e);
                                }}
                                ghost
                                disabled={_disabled}
                                text="移除"
                                style={{ marginLeft: 8 }}
                                type="danger"
                            />
                            <AdButton
                                type="primary"
                                disabled={false}
                                onClick={e => {
                                    this.addInfoInd(e);
                                }}
                                style={{ marginLeft: 8 }}
                                text="添加"
                            />
                            <AdButton
                                type="primary"
                                disabled={false}
                                onClick={e => {
                                    this.pullInfoInd(e);
                                }}
                                style={{ marginLeft: 8 }}
                                text="拉取杂费"
                            />
                        </div>
                    ),
                },
                {
                    key: preTitle,
                    extra: (
                        <>
                            <AdButton
                                onClick={e => {
                                    this.removeInfoPre(e);
                                }}
                                ghost
                                // code={codes.delPressure}
                                disabled={disabled || selectedRowsPre.length === 0}
                                text="移除"
                                type="danger"
                            />
                            <AdButton
                                type="primary"
                                // code={codes.addPressure}
                                disabled={disabled}
                                onClick={e => {
                                    this.addInfoPre(e);
                                }}
                                style={{ marginLeft: 8 }}
                                text="添加压夜"
                            />
                        </>
                    ),
                },
            ],
        };
        const commonParams = {
            getFieldDecorator,
        };

        const prefixSelector = (name, value) => (
            <AntdFormItem code={name} initialValue={value || undefined} {...commonParams}>
                <AdSelect
                    disabled={true}
                    data={dictObject[allDictList.currencyType]}
                    payload={{ code: allDictList.currencyType }}
                />
            </AntdFormItem>
        );

        const formItem = [
            [
                <AntdFormItem
                    label="车次号"
                    code="trainNo"
                    initialValue={detailHK.trainNo}
                    {...commonParams}
                >
                    <AntdInput placeholder='请输入' disabled={true} />
                </AntdFormItem>,
                <AntdFormItem
                    label="类型"
                    code="businessType"
                    initialValue={detail.businessType || 'INLAND'}
                    {...commonParams}
                >
                    <AdSelect
                        disabled={disabled}
                        data={dictObject[allDictList.businessType]}
                        payload={{ code: allDictList.businessType }}
                        onChange={(value) => this.getValue(value, 'businessType')}
                    />
                </AntdFormItem>,
            ],
            [
                // <Form.Item label="状态">
                //     {getFieldDecorator('status', {
                //         initialValue: detail.status,
                //     })(
                //         <Select disabled={true}>
                //             {archivesStatusList &&
                //                 archivesStatusList.map(item => <Option key={item.code}>{item.value}</Option>)}
                //         </Select>
                //     )}
                // </Form.Item>,
                <AntdFormItem
                    label="车次状态"
                    code="trainStatus" //不可编辑，可不传至后台
                    initialValue={detailHK.status}
                    {...commonParams}
                >
                    <AntdInput placeholder='请输入' disabled={true} />
                </AntdFormItem>,
                <AntdFormItem
                    label="车次车牌号"
                    code="cartPlate"
                    initialValue={detail.cartPlate}
                    {...commonParams}
                >
                    <AntdInput placeholder='' disabled={true} />
                </AntdFormItem>,
            ],
            [
                <AntdFormItem
                    label="车次运费"
                    code="freight"
                    initialValue={formatPrice(detailHK.freight)}
                    {...commonParams}
                >
                    <AntdInput
                        mode="money"
                        addonBefore={prefixSelector('currencyType', detailHK.currencyType || 'CNY')}
                        disabled={true}
                    />
                </AntdFormItem>,
                <AntdFormItem
                    label="车次计费车型"
                    code="pricingModels"
                    initialValue={detailHK ? detailHK.pricingModels : undefined}
                    {...commonParams}
                >
                    <AntdInput placeholder='请输入' disabled={true} />
                </AntdFormItem>
            ],

            [
                <AntdFormItem
                    label="车次始发地"
                    initialValue={detailHK.hkOrigin}
                    code="hkOrigin"
                    {...commonParams}
                >
                    <AntdInput placeholder='' disabled={true} />
                </AntdFormItem>,
                <AntdFormItem
                    label="车次目的地"
                    initialValue={detailHK.hkDestination}
                    code="hkDestination"
                    {...commonParams}
                >
                    <AntdInput placeholder='' disabled={true} />
                </AntdFormItem>
            ],
            [
                <AntdFormItem
                    label="发车时间"
                    code="transportStartTime"
                    initialValue={
                        detail && detailHK && detailHK.transportStartTime
                            ? moment(detailHK.transportStartTime, dateFormatTime)
                            : null
                    }
                    {...commonParams}
                >
                    <AntdDatePicker showTime disabled={true} />
                </AntdFormItem>,
                <AntdFormItem
                    label="收车时间"
                    code="transportEndTime"
                    initialValue={
                        detail && detailHK && detailHK.transportEndTime ? moment(detailHK.transportEndTime, dateFormatTime) : null
                    }
                    {...commonParams}
                >
                    <AntdDatePicker showTime disabled={true} placeholder='请选择日期' />
                </AntdFormItem>,
            ],

            [
                <Divider dashed />
            ],

            [

                <AntdFormItem
                    label="是否查验"
                    code="check"
                    initialValue={detailHK.check || false}
                    rules={[{ required: true }]}
                    {...commonParams}
                >
                    <Radio.Group >
                        <Radio value={false} disabled={disabled}>
                            否
           </Radio>
                        <Radio value={true} disabled={disabled}>
                            是
           </Radio>
                    </Radio.Group>
                </AntdFormItem>,
                <AntdFormItem
                    label="业务类型"
                    code="trainBusinessType"
                    initialValue={detailHK.trainBusinessType || ''}
                    {...commonParams}
                >
                    <Radio.Group >
                        <Radio value="EXPORT" disabled={disabled}>
                            出口
       </Radio>
                        <Radio value="IMPORT" disabled={disabled}>
                            进口
       </Radio>
                    </Radio.Group>
                </AntdFormItem>,
            ],

            [
                <AntdFormItem
                    label="柜型类别"
                    code="carType"
                    rules={[{ required: true }]}
                    initialValue={detailHK.carType}
                    {...commonParams}
                >
                    <AdSelect
                        disabled={disabled}
                        data={dictObject[allDictList.cabinetTypeHK]}
                        payload={{ code: allDictList.cabinetTypeHK }}
                    // filterValue={['MA_CAR']}
                    />
                </AntdFormItem>,
                <AntdFormItem
                    label="司机"
                    code="driverIds"
                    initialValue={drivers}
                    rules={[{ required: true }]}
                    {...commonParams}
                >
                    <SearchSelect
                        dataUrl="tms/tms-driver-archives/selectDriverList"
                        url="tms/tms-driver-archives/selectDriverView_s"
                        multiple={true} // 是否多选
                        selectedData={drivers} // 选中值
                        columns={columnsDriver} // 表格展示列
                        onChange={val => this.getValue(val, 'drivers')} // 获取选中值
                        id="ArchivesOperate_2"
                        disabled={disabled}
                        allowClear={false}
                        // scrollX={350}
                        placeholder='请输入'
                    // payload={{ mdsCompanyId: 'HW01' }}
                    />
                </AntdFormItem>,
            ],
            [<AntdFormItem
                label="结算周期"
                code="settlementDate"
                rules={[{ required: true }]}
                initialValue={
                    detail && detail.settlementDate
                        ? moment(detail.settlementDate, dateFormatByM)
                        : null
                }
                {...commonParams}
            >
                <MonthPicker disabled={disabled} style={{ width: "100%" }} />
            </AntdFormItem>,
            <AntdFormItem
                label="口岸"
                initialValue={detailHK.transit}
                code="transit"
                name="transit"
                {...commonParams}
            >
                {/* <AntdInput placeholder='请输入'  disabled={disabled} autoComplete="on"/> */}

                {/* antd4.0+ */}
                {/* <AutoComplete
                    style={{ width: 200 }}
                    options={placeHKList}
                    placeholder="请输入"
                    filterOption={(inputValue, option) =>
                        option.value.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1
                    }
                /> */}
                {/* antd3.0+ */}
                <AutoComplete
                    style={{ width: "100%" }}
                    dataSource={placeHKList}
                    placeholder="请输入"
                    filterOption={(inputValue, option) => {
                        return option.props.children.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1
                    }
                    }
                />
            </AntdFormItem>],
            [
                <AntdFormItem
                    label="始发地"
                    initialValue={detailHK.origin}
                    code="origin"
                    {...commonParams}
                >
                    <AntdInput placeholder='请输入' name="origin" disabled={disabled} autoComplete="on" />
                </AntdFormItem>,
                <AntdFormItem
                    label="目的地"
                    initialValue={detailHK.destination}
                    code="destination"
                    {...commonParams}
                >
                    <AntdInput placeholder='请输入' name="destination" disabled={disabled} autoComplete="on" />
                </AntdFormItem>
            ],
            [
                <AntdFormItem
                    label="直派地"
                    initialValue={detailHK.straightAddress || '无'}
                    code="straightAddress"
                    {...commonParams}
                >
                    <AdSelect
                        data={dictObject[allDictList.straightAddress]}
                        payload={{ code: allDictList.straightAddress }}
                        disabled={disabled}
                    />
                </AntdFormItem>,
                <AntdFormItem
                    label="提派点"
                    initialValue={detailHK.sendSome || '1'}
                    code="sendSome"
                    {...commonParams}
                >
                    <AdSelect isExist={true} data={sendSomeList} disabled={disabled} />
                </AntdFormItem>,
            ],
            [
                <AntdFormItem
                    label="渡柜司机"
                    initialValue={this.state.hkDriver}
                    code="hkDriver"
                    {...commonParams}
                >
                    <SearchSelect
                        dataUrl="tms/tms-driver-archives/selectDriverList"
                        url="tms/tms-driver-archives/selectDriverView_s"
                        multiple={false} // 是否多选
                        selectedData={this.state.hkDriver} // 选中值
                        columns={columnsDriver} // 表格展示列
                        onChange={val => this.getValue(val, 'hkDriver')} // 获取选中值
                        id="hkDriver"
                        disabled={disabled}
                        allowClear={true}
                        // scrollX={350}
                        placeholder='请输入'
                    // payload={{ mdsCompanyId: 'HW01' }}
                    />
                </AntdFormItem>,
                <AntdFormItem
                    label="渡柜中转地"
                    initialValue={detailHK.hkTransit || ''}
                    code="hkTransit"
                    {...commonParams}
                >
                    <AutoComplete
                    style={{ width: "100%" }}
                    dataSource={crossHkList}
                    disabled={disabled}
                    placeholder="请输入"
                    filterOption={(inputValue, option) => {
                        return option.props.children.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1
                    }
                    }
                />
                </AntdFormItem>,
            ],

            [
                <AntdFormItem
                    label="备注"
                    code="remarks"
                    rules={[
                        {
                            validator: (rule, value, callback) => {
                                checkStrLength(rule, value, callback, 500, '备注');
                            },
                        },
                    ]}
                    initialValue={detailHK.remarks}
                    {...commonParams}
                >
                    <AntdInput
                        maxlen={500}
                        disabled={disabled}
                        type="textarea"
                        placeholder='请输入不超过500字符'
                        autoComplete="on"
                    />
                </AntdFormItem>,
            ],
            [
                <AntdFormItem
                    label="附件"
                    code="attaQuantity"
                    initialValue={detail.fileList || []}
                    {...commonParams}
                >
                    <FileReader urlType="tms" disabled={disabled} />
                </AntdFormItem>,
            ],
        ];

        return (
            <Fragment>
                {visibleRemove && <AdModal
                    visible={visibleRemove}
                    title={'移除'}
                    onOk={this.removeInfoInd}
                    onCancel={() => this.setState({ visibleRemove: false })}
                    width="40%"
                    style={{
                        maxWidth: 500,
                    }}
                >
                    {'请确认是否移除该单据号'}
                </AdModal>}
                <EditPage {...editPageParams}>
                    <Spin spinning={detailId ? loading : false}>
                        <AntdForm>{formItemFragement(formItem)}</AntdForm>
                    </Spin>
                    {detailId && detail.status !== 'UNSEALED' && (
                        <Fragment>
                            <ArchivesDriverslInfo businessType={detail.businessType} archivesId={detailId} isHK={isHK} />
                        </Fragment>
                    )}
                    <Fragment>
                        <div className={styles.customPartsOfferInfo}>
                            <AntdForm>
                                <StandardTable
                                    loading={loading}
                                    data={dataInd}
                                    columns={this.columns}
                                    selectedRows={selectedRowsInd}
                                    disabledRowSelected={false}
                                    pagination={false}
                                    scrollX={1400}
                                    scrollY={400}
                                    canInput={true}
                                    onSelectRow={selectedRowsInd => this.handleStateChange([{ selectedRowsInd }])}
                                />
                            </AntdForm>
                        </div>
                    </Fragment>
                    <Fragment>
                        {/* 添加压夜 表格 */}
                        <PressureInfo
                            archivesId={detailId}
                            onlyRead={false}
                            driversIID={{ 'driverSort': driversIID }}
                            onRef={this.onRef}
                            selectedRows={selectedRowsPre}
                            disabled={disabled}
                            onSelectRow={selectedRowsPre => this.handleStateChange([{ selectedRowsPre }])}
                            showTipsFun={this.showTipsFun}
                            isHK={isHK}
                            trainInfo={{ trainId: detailHK.id, trainNo: detailHK.trainNo }}
                        />
                    </Fragment>

                </EditPage>
            </Fragment>

        );
    }
}
